package tyk.Servlet;

import tyk.Service.BookService;
import tyk.pojo.Book;
import tyk.pojo.Cart;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/***
 *@title $NAME
 *@description <TODO description class purpose>
 *@author Tang'ya'kang
 *@VERSION 1.0.0
 *@CREATE 2023/5/17 22:27
 **/
public class CartServlet extends HttpServlet {
    public void addItem(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Cart cart;
        cart = (Cart) request.getSession().getAttribute("cart");
        if (cart == null) {
            cart=new Cart();
        }
        Integer id= Integer.valueOf(request.getParameter("id"));
        Book book= (Book) new BookService().SelectById(id).get(0);
        cart.add(book);
        request.getSession().setAttribute("cart",cart);
        response.sendRedirect(request.getHeader("referer"));
    }
    public void DeleteById(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Cart cart;
        cart = (Cart) request.getSession().getAttribute("cart");
        Integer id= Integer.valueOf(request.getParameter("id"));
        cart.DeleteById(id);
        request.getSession().setAttribute("cart",cart);
        response.sendRedirect(request.getHeader("referer"));
    }
    public void Clear(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Cart cart;
        cart = (Cart) request.getSession().getAttribute("cart");
        cart.Clear();
        request.getSession().setAttribute("cart",cart);
        response.sendRedirect(request.getHeader("referer"));
    }
    public void Update(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Integer id= Integer.valueOf(request.getParameter("id"));
        Integer count= Integer.valueOf(request.getParameter("count"));
        Cart cart;
        cart = (Cart) request.getSession().getAttribute("cart");
        cart.Update(id,count);
        request.getSession().setAttribute("cart",cart);
        response.sendRedirect(request.getHeader("referer"));
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String hidden=request.getParameter("action");
        try {
            Method method = this.getClass().getDeclaredMethod(hidden,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(this,request,response);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

}
